




import cn.hutool.core.text.StrBuilder;
import cn.iocoder.yudao.module.promotion.dal.dataobject.banner.BannerDO;
import cn.iocoder.yudao.module.promotion.dal.dataobject.bargain.BargainActivityDO;
import cn.iocoder.yudao.module.promotion.dal.dataobject.combination.CombinationRecordDO;

import java.io.*;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CreateMysql {

    public static void main(String[] a) {
        // 实体类的位置
        List<Class> classList = Arrays.asList(
                CombinationRecordDO.class
        );
        // 生成的sql语句的位置
        String outputPath = "D:\\excel\\user.txt";
        StrBuilder sb = new StrBuilder();
        classList.forEach(x->{
            String sql = generateTableSql(x, null);
            sb.append(sql);
            sb.append("\n");
        });
        writeFile(sb.toString(), outputPath);

        System.out.println("生成结束");
    }

    public static void writeFile(String content, String outputPath) {
        File file = new File(outputPath);
        System.out.println("文件路径: " + file.getAbsolutePath());
        // 输出文件的路径
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        BufferedWriter out = null;

        try {
            // 如果文件存在，就删除
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            fos = new FileOutputStream(file, true);
            osw = new OutputStreamWriter(fos);
            out = new BufferedWriter(osw);
            out.write(content);
            // 清空缓冲流，把缓冲流里的文本数据写入到目标文件里
            out.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String generateTableSql(Class obj,  String tableName) {
        // tableName 如果是 null，就用类名做表名
        if (tableName == null || tableName.equals("")) {
            tableName = obj.getName();
            tableName = tableName.substring(tableName.lastIndexOf(".") + 1);
            tableName = upperCharToUnderLine(tableName);

        }
        // 表名用大写字母
//        tableName = tableName.toUpperCase();

        Field[] fields = obj.getDeclaredFields();

        String column;

        StringBuilder sb = new StringBuilder();

        sb.append("drop table if exists ").append(tableName).append(";\r\n");

        sb.append("\r\n");

        sb.append("create table ").append(tableName).append("(\r\n");
        System.out.println(tableName);


        for (int i = 1; i < fields.length; i++) {
            Field f = fields[i];

            column = f.getName();


            Class<?> type = f.getType();
            System.out.println(column + ", " + type.getSimpleName());
            String typeName = type.getTypeName();
            column=upperCharToUnderLine(column);
            sb.append( column); // 一般第一个是主键

            if (typeName.equals("java.lang.Integer")) {
                sb.append(" int(11) ");
            } else if (typeName.equals("java.lang.Long")) {
                sb.append(" bigint(20) ");
            } else if (typeName.equals("java.lang.Float")) {
                sb.append(" float(11,5) ");
            } else if (typeName.equals("java.time.LocalDate")) {
                sb.append(" date ");
            } else if (typeName.equals("java.time.LocalDateTime") || typeName.equals("java.util.Date")) {
                sb.append(" datetime ");
            } else {
                // 注意：根据需要，自行修改 varchar 的长度。这里设定为长度等于 50
                sb.append(" varchar(" + 50 + ") " );
            }
            if (column.equals("id")){
                sb.append(" not null AUTO_INCREMENT ");

            }
            // todo 增加对字段的注解的处理
            sb.append(", ");

            sb.append("\n");
        }
        Field f = fields[1];

        column = f.getName();
        column=upperCharToUnderLine(column);
        sb.append(" PRIMARY KEY (`");
        sb.append(column);
        sb.append("`) USING BTREE");
        String sql = sb.toString();

        sql = sb.substring(0, sql.length()) + "\n) " + "ENGINE = INNODB DEFAULT CHARSET = utf8mb4;";
        return sql;
    }

    public static String upperCharToUnderLine(String param) {
        Pattern p = Pattern.compile("[A-Z]");
        if (param == null || param.equals("")) {
            return "";
        }
        StringBuilder builder = new StringBuilder(param);
        Matcher mc = p.matcher(param);
        int i = 0;
        while (mc.find()) {

            builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
            i++;
        }

        if ('_' == builder.charAt(0)) {
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }

}
